<template>
  <view class="throw-bottle-container planet-bg">
    <!-- 星空背景 -->
    <view class="stars">
      <view v-for="star in stars" :key="star.id" class="star" :style="star.style"></view>
    </view>
    
    <!-- 页面标题 -->
    <view class="header">
      <text class="title">扔出漂流瓶</text>
      <text class="subtitle">将你的心声投向宇宙的海洋</text>
    </view>
    
    <!-- 主要内容区 -->
    <view class="main-content">
      <!-- 漂流瓶内容输入 -->
      <view class="input-section">
        <textarea 
          class="content-input"
          placeholder="写下你想对宇宙说的话..."
          placeholder-style="color: rgba(255, 255, 255, 0.5)"
          v-model="bottleContent"
          maxlength="200"
          @input="checkContentLength"
        ></textarea>
        <text class="char-count">{{ contentLength }}/200</text>
      </view>
      
      <!-- 选择发送的星球 -->
      <view class="planet-selection">
        <text class="section-title">选择目标星球</text>
        <view class="planets-grid">
          <view 
            class="planet-item" 
            v-for="planet in planets" 
            :key="planet.id"
            :class="{ 'selected': selectedPlanet === planet.id }"
            @tap="selectPlanet(planet.id)"
          >
            <view class="planet-icon" :style="{ '--planet-color': planet.color }"></view>
            <text class="planet-name">{{ planet.name }}</text>
          </view>
        </view>
      </view>
      
      <!-- 漂流瓶预览 -->
      <view class="bottle-preview" v-if="bottleContent.trim()">
        <text class="section-title">漂流瓶预览</text>
        <view class="bottle">
          <view class="bottle-neck"></view>
          <view class="bottle-body">
            <text class="bottle-text">{{ bottleContent || '你的漂流瓶内容将显示在这里' }}</text>
          </view>
          <view class="bottle-cap"></view>
        </view>
      </view>
      
      <!-- 扔瓶按钮 -->
      <button 
        class="btn btn-primary throw-btn"
        @tap="throwBottle"
        :disabled="!canThrow || isThrowing"
      >
        {{ isThrowing ? '扔出中...' : '🚀 扔出漂流瓶' }}
      </button>
      
      <!-- 发送统计 -->
      <view class="stats">
        <text class="stat-item">今日已扔: {{ todayThrown }}个</text>
        <text class="stat-item">总发送: {{ totalThrown }}个</text>
      </view>
    </view>
    
    <!-- 底部提示 -->
    <view class="footer">
      <text class="tip-text">💡 每天最多可扔出3个漂流瓶</text>
    </view>
  </view>
</template>

<script>
  import { throwBottle as throwBottleApi } from '../../src/api/bottle/bottleApi';
  import { showToast, generateId } from '../../src/common/tools';
  
  export default {
    data() {
      return {
        bottleContent: '',
        contentLength: 0,
        selectedPlanet: 'random', // 默认随机星球
        isThrowing: false,
        todayThrown: 0,
        totalThrown: 0,
        // 星球列表
        planets: [
          { id: 'random', name: '随机星球', color: '#FFD700' },
          { id: 'earth', name: '地球', color: '#228B22' },
          { id: 'mars', name: '火星', color: '#B22222' },
          { id: 'venus', name: '金星', color: '#FF6347' },
          { id: 'jupiter', name: '木星', color: '#DAA520' },
          { id: 'saturn', name: '土星', color: '#F4A460' }
        ],
        stars: []
      };
    },
    computed: {
      // 检查是否可以扔漂流瓶
      canThrow() {
        return this.bottleContent.trim().length >= 10 && this.todayThrown < 3;
      }
    },
    onLoad() {
      // 初始化星空背景
      this.initStars();
      // 加载发送统计
      this.loadStats();
    },
    methods: {
      // 初始化星空背景
      initStars() {
        const starCount = 150;
        const tempStars = [];
        
        for (let i = 0; i < starCount; i++) {
          // 随机位置
          const x = Math.random() * 100;
          const y = Math.random() * 100;
          
          // 随机动画时长
          const duration = 2 + Math.random() * 3;
          
          // 随机大小
          const size = 1 + Math.random() * 3;
          
          // 随机透明度
          const opacity = 0.3 + Math.random() * 0.7;
          
          tempStars.push({
            id: `star-${i}`,
            style: {
              left: `${x}%`,
              top: `${y}%`,
              width: `${size}rpx`,
              height: `${size}rpx`,
              opacity: opacity,
              '--duration': `${duration}s`
            }
          });
        }
        
        this.stars = tempStars;
      },
      
      // 加载发送统计
      loadStats() {
        // 从本地存储获取统计数据
        const today = new Date().toDateString();
        const lastThrowDate = uni.getStorageSync('lastThrowDate');
        const savedTodayThrown = uni.getStorageSync('todayThrown');
        const savedTotalThrown = uni.getStorageSync('totalThrown');
        
        // 如果日期不同，重置今日发送数
        if (lastThrowDate !== today) {
          this.todayThrown = 0;
          uni.setStorageSync('todayThrown', 0);
          uni.setStorageSync('lastThrowDate', today);
        } else {
          this.todayThrown = savedTodayThrown || 0;
        }
        
        this.totalThrown = savedTotalThrown || 0;
      },
      
      // 检查内容长度
      checkContentLength() {
        this.contentLength = this.bottleContent.length;
      },
      
      // 选择目标星球
      selectPlanet(planetId) {
        this.selectedPlanet = planetId;
      },
      
      // 扔出漂流瓶
      async throwBottle() {
        if (!this.canThrow) {
          if (this.todayThrown >= 3) {
            showToast('今日发送已达上限，请明天再来');
          } else {
            showToast('漂流瓶内容至少需要10个字符');
          }
          return;
        }
        
        try {
          this.isThrowing = true;
          
          // 创建漂流瓶数据
          const bottleData = {
            id: generateId(),
            content: this.bottleContent.trim(),
            from: this.selectedPlanet === 'random' ? '随机位置' : this.planets.find(p => p.id === this.selectedPlanet).name,
            time: new Date().toISOString()
          };
          
          // 模拟网络延迟
          await new Promise(resolve => setTimeout(resolve, 2000));
          
          // 更新统计数据
          this.todayThrown++;
          this.totalThrown++;
          
          // 保存到本地存储
          uni.setStorageSync('todayThrown', this.todayThrown);
          uni.setStorageSync('totalThrown', this.totalThrown);
          
          // 清空输入框
          this.bottleContent = '';
          this.contentLength = 0;
          
          // 显示成功提示
          showToast('🌊 漂流瓶已成功扔出！', 'success');
          
          // 添加动画效果
          this.animateBottleThrow();
          
        } catch (error) {
          console.error('扔出漂流瓶失败', error);
          showToast('扔出失败，请重试');
        } finally {
          this.isThrowing = false;
        }
      },
      
      // 漂流瓶扔出动画
      animateBottleThrow() {
        // 这里可以添加一些动画效果，比如漂流瓶飞入太空
        const bottles = document.querySelectorAll('.bottle');
        if (bottles.length > 0) {
          const bottle = bottles[0];
          bottle.style.transition = 'all 1s ease-out';
          bottle.style.transform = 'translateY(-500rpx) rotate(360deg) scale(0.1)';
          bottle.style.opacity = '0';
          
          // 重置动画
          setTimeout(() => {
            bottle.style.transition = 'none';
            bottle.style.transform = 'translateY(0) rotate(0) scale(1)';
            bottle.style.opacity = '1';
          }, 1000);
        }
      }
    }
  };
</script>

<style scoped>
  @import '../../src/style/global.scss';
  
  .throw-bottle-container {
    width: 100%;
    min-height: 100vh;
    padding: 40rpx 30rpx;
    color: var(--white);
    position: relative;
  }
  
  .header {
    text-align: center;
    margin-bottom: 50rpx;
  }
  
  .title {
    font-size: 48rpx;
    font-weight: bold;
    display: block;
    margin-bottom: 10rpx;
  }
  
  .subtitle {
    font-size: 28rpx;
    opacity: 0.8;
    display: block;
  }
  
  .main-content {
    display: flex;
    flex-direction: column;
    align-items: center;
  }
  
  .input-section {
    width: 100%;
    margin-bottom: 40rpx;
    position: relative;
  }
  
  .content-input {
    width: 100%;
    min-height: 240rpx;
    padding: 30rpx;
    background-color: rgba(255, 255, 255, 0.1);
    border-radius: 20rpx;
    color: var(--white);
    font-size: 28rpx;
    line-height: 1.6;
    backdrop-filter: blur(10rpx);
  }
  
  .char-count {
    position: absolute;
    bottom: 10rpx;
    right: 20rpx;
    font-size: 22rpx;
    opacity: 0.7;
  }
  
  .planet-selection {
    width: 100%;
    margin-bottom: 40rpx;
  }
  
  .section-title {
    font-size: 32rpx;
    font-weight: bold;
    margin-bottom: 20rpx;
    display: block;
  }
  
  .planets-grid {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 20rpx;
  }
  
  .planet-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 20rpx;
    border-radius: 15rpx;
    background-color: rgba(255, 255, 255, 0.1);
    transition: all 0.3s ease;
  }
  
  .planet-item.selected {
    background-color: rgba(255, 255, 255, 0.2);
    transform: scale(1.05);
  }
  
  .planet-icon {
    width: 80rpx;
    height: 80rpx;
    border-radius: 50%;
    background-color: var(--planet-color);
    margin-bottom: 10rpx;
    box-shadow: 0 0 20rpx var(--planet-color);
  }
  
  .planet-name {
    font-size: 24rpx;
    opacity: 0.9;
  }
  
  .bottle-preview {
    width: 100%;
    margin-bottom: 40rpx;
  }
  
  .bottle {
    width: 200rpx;
    height: 280rpx;
    margin: 0 auto;
    position: relative;
    animation: float 3s ease-in-out infinite;
  }
  
  .bottle-neck {
    width: 60rpx;
    height: 40rpx;
    background-color: rgba(255, 255, 255, 0.8);
    position: absolute;
    top: -40rpx;
    left: 50%;
    transform: translateX(-50%);
  }
  
  .bottle-body {
    width: 200rpx;
    height: 240rpx;
    background-color: rgba(255, 255, 255, 0.8);
    border-radius: 0 0 100rpx 100rpx;
    position: relative;
    overflow: hidden;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 30rpx;
  }
  
  .bottle-text {
    font-size: 24rpx;
    color: var(--text-color);
    text-align: center;
    line-height: 1.4;
  }
  
  .bottle-cap {
    width: 80rpx;
    height: 20rpx;
    background-color: #8B4513;
    position: absolute;
    top: -60rpx;
    left: 50%;
    transform: translateX(-50%);
    border-radius: 10rpx;
  }
  
  .throw-btn {
    width: 100%;
    max-width: 400rpx;
    height: 100rpx;
    font-size: 32rpx;
    font-weight: bold;
    margin-bottom: 40rpx;
  }
  
  .stats {
    display: flex;
    justify-content: center;
    margin-bottom: 30rpx;
  }
  
  .stat-item {
    font-size: 24rpx;
    opacity: 0.8;
    margin: 0 20rpx;
  }
  
  .footer {
    text-align: center;
  }
  
  .tip-text {
    font-size: 24rpx;
    opacity: 0.7;
  }
  
  /* 动画定义 */
  @keyframes float {
    0%, 100% {
      transform: translateY(0) rotate(0deg);
    }
    50% {
      transform: translateY(-20rpx) rotate(5deg);
    }
  }
</style>